// pages/teacher/edit-profile/edit-profile.js
// 与学生端共享同样的逻辑
Page({
  data: {
    userInfo: {
      name: '',
      phone: '',
      email: '',
      avatar: '',
      level: ''
    }
  },
  onLoad() {
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo) {
      this.setData({
        userInfo: {
          name: userInfo.name || '',
          phone: userInfo.phone || '',
          email: userInfo.email || '',
          avatar: userInfo.avatar || '',
          level: userInfo.level || ''
        }
      })
    }
  },
  handleNameInput(e) {
    this.setData({ 'userInfo.name': e.detail.value })
  },
  handlePhoneInput(e) {
    this.setData({ 'userInfo.phone': e.detail.value })
  },
  handleEmailInput(e) {
    this.setData({ 'userInfo.email': e.detail.value })
  },
  chooseAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.setData({
          'userInfo.avatar': res.tempFilePaths[0]
        })
        wx.showToast({ title: '头像已更新', icon: 'success' })
      }
    })
  },
  saveProfile() {
    const { name, phone } = this.data.userInfo
    if (!name || !phone) {
      wx.showToast({ title: '请填写必填信息', icon: 'none' })
      return
    }
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      wx.showToast({ title: '手机号格式不正确', icon: 'none' })
      return
    }
    
    wx.showLoading({ title: '保存中...' })
    setTimeout(() => {
      const savedUserInfo = wx.getStorageSync('userInfo')
      wx.setStorageSync('userInfo', { 
        ...savedUserInfo, 
        name: this.data.userInfo.name,
        avatar: this.data.userInfo.avatar,
        phone: this.data.userInfo.phone,
        email: this.data.userInfo.email
      })
      wx.hideLoading()
      wx.showToast({ title: '保存成功', icon: 'success' })
      setTimeout(() => wx.navigateBack(), 1500)
    }, 1000)
  }
})
